﻿using FPSO.Models.TagMapping;
using MySqlX.XDevAPI.Relational;
using PDB.DotNetSDK;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace FPSO.Services.Impl
{
    public class SnapTSService : ITSService
    {
        public string ConnStr { get; set; }
        private PDBConnection conn = null;

        public List<TagValue> GetIntValues(string table, List<long> idList)
		{
			List<TagValue> resultList = new List<TagValue>();
			if (idList == null || idList.Count == 0)
			{
				return resultList;
			}

			string querySql = string.Format("SELECT * FROM {0}.snapshot WHERE devid IN ({1}) LIMIT 10000",
				table, string.Join(",", idList));
			DataTable dt = queryData(querySql);
			foreach (DataRow dr in dt.Rows)
			{
				long devId = (long)dr[0];
				DateTime tstamp = (DateTime)dr[1];
				int value = (int)dr[2];

				//long devId = (long)dr["devid"];
				//DateTime tstamp = (DateTime)dr["tstamp"];
				//int value = (int)dr["val"];
				resultList.Add(new TagValue(devId, TypeCode.Int32) { TStamp = tstamp, Value = value });
			}
			return resultList;
		}

        public TagInfo GetTagInfo(string table, string tagName)
        {
            string querySql = string.Format("SELECT * FROM sys_dev WHERE tabname='{0}' AND devname='{1}'", table, tagName);
            using (PDBConnection conn = new PDBConnection(ConnStr))
            {
				//DEBUG 加入PDB无法加载的处理
				try
				{
					conn.Open();
					PDBCommand cmd = conn.CreateCommand();
					DataTable result = cmd.ExecuteQuery(querySql);
					if (result != null && result.Rows.Count > 0)
					{
						TagInfo tagInfo = new TagInfo();
						tagInfo.TabName = (string)result.Rows[0]["tabname"];
						tagInfo.TagID = (long)result.Rows[0]["devid"];
						tagInfo.TagName = (string)result.Rows[0]["devname"];
						return tagInfo;
					}
				}
				catch(Exception ex) 
				{
				}
            }

            throw new Exception(string.Format("表[{0}]中不存在标签[{1}]", table, tagName));
        }

        public List<TagInfo> GetTagInfo(string table, List<string> tagName)
        {
            const int batchSize = 500;
            List<TagInfo> tagList = new List<TagInfo>();
            using (PDBConnection conn = new PDBConnection(ConnStr))
            {
				//DEBUG 加入PDB无法加载的处理
				try
				{
					conn.Open();
					PDBCommand cmd = conn.CreateCommand();
					int bgIdx = 0;
					while (bgIdx < tagName.Count)
					{
						int batch = Math.Min(tagName.Count - bgIdx, batchSize);
						List<string> tmpNameList =
						  tagName.Skip(bgIdx).Take(batch).Select(t => string.Format("'{0}'", t)).ToList();
						string querySql = string.Format("SELECT * FROM sys_dev WHERE tabname = '{0}' AND devname IN ({1})",
						  table, string.Join(",", tmpNameList));
						DataTable dt = cmd.ExecuteQuery(querySql);
						foreach (DataRow dr in dt.Rows)
						{
							TagInfo tagInfo = new TagInfo();
							tagInfo.TabName = (string)dr["tabname"];
							tagInfo.TagID = (long)dr["devid"];
							tagInfo.TagName = (string)dr["devname"];
							tagList.Add(tagInfo);
						}
						bgIdx += batch;
					}
				}
				catch (Exception ex) 
				{

				}
            }

            return tagList;
        }

		//DEBUG 不依赖pinus建立tagList
		public List<TagInfo> GetTagInfo(List<string> tagName)
		{
			List<TagInfo> tagList = new List<TagInfo>();
			for(int i=0;i< tagName.Count;i++)
			{
				TagInfo tagInfo = new TagInfo();
				string tag = tagName[i];
				tagInfo.TabName = "";
				tagInfo.TagID = 10000+i;
				tagInfo.TagName = tag;
				tagList.Add(tagInfo);
			}
			return tagList;
		}

		public List<TagValue> GetIntValues(List<string> nameList)
		{
			List<TagValue> resultList = new List<TagValue>();
			if (nameList == null || nameList.Count == 0)
			{
				return resultList;
			}

			//foreach (DataRow dr in dt.Rows)
			//{
			//	long devId = (long)dr[0];
			//	DateTime tstamp = (DateTime)dr[1];
			//	int value = (int)dr[2];

			//	//long devId = (long)dr["devid"];
			//	//DateTime tstamp = (DateTime)dr["tstamp"];
			//	//int value = (int)dr["val"];
			//	resultList.Add(new TagValue(devId, TypeCode.Int32) { TStamp = tstamp, Value = value });
			//}
			return resultList;
		}

		private DataTable queryData(string querySql)
		{
			try
			{
				if (conn == null)
				{
					conn = new PDBConnection(ConnStr);
					conn.Open();
				}

				PDBCommand cmd = conn.CreateCommand();
				return cmd.ExecuteQuery(querySql);
			}
			catch (Exception ex)
			{
				conn = null;
				throw ex;
			}
		}
    }
}
